package cn.lg.soar.common.util.trans.jackson;

import cn.lg.soar.common.util.trans.handler.ITranslateHandler;
import cn.lg.soar.common.util.trans.model.TranslateContext;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Objects;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class TranslateSerializer<T, A extends Annotation> extends JsonSerializer<T> {

    protected static final Logger LOGGER = LoggerFactory.getLogger(TranslateSerializer.class);

    private final TranslateContext<T> translateContext;
    private final ITranslateHandler handler;
    private final A annotation;
    private final String fieldName;

    public TranslateSerializer(TranslateContext<T> translateContext, A annotation) {
        this.annotation = annotation;
        this.translateContext = translateContext;
        this.handler = translateContext.getHandler();
        this.fieldName = translateContext.getTranslateName();
    }

    @Override
    public void serialize(T o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        try {
            Object translateValue = o == null ? null : handler.convertByJava(o, annotation, translateContext);
            String currentName = jsonGenerator.getOutputContext().getCurrentName();
            if (fieldName == null) {
                jsonGenerator.writeObject(o);
                jsonGenerator.writeFieldName(currentName + "Name");
                jsonGenerator.writeObject(translateValue);
            } else if (Objects.equals(currentName, fieldName)) {
                jsonGenerator.writeObject(translateValue);
            } else {
                // 写原始字段的值
                jsonGenerator.writeObject(o);
                // 新增字段
                jsonGenerator.writeFieldName(fieldName);
                jsonGenerator.writeObject(translateValue);
            }
        } catch (RuntimeException e) {
            LOGGER.error("翻译异常：{}", o, e);
            // 写原始字段的值
            jsonGenerator.writeObject(o);
        }
    }

}
